import { Dialog, Message, Upload } from '@alifd/next';
import { useImperativeHandle, useRef, forwardRef } from 'react';
import { baseURL } from '@/config/backendUrl';
import { ObjectFile } from '@alifd/next/types/upload/types';

export interface UploadCardRef {
  uploadOK: () => void;
}

interface UploadCardProps {
  onUpdate: () => void;
}

const UploadCard = ({ onUpdate }: UploadCardProps, ref) => {
  // 定义允许的文件类型（可配置为常量）
  const ALLOWED_MIME_TYPES = [
    'image/png',
    'image/jpg',
    'image/jpeg',
    'image/gif',
    'image/bmp',
  ];
  // 获取用户凭证
  const token = localStorage.getItem('token');
  // 上传组件Ref
  const uploaderRef = useRef<InstanceType<typeof Upload.Card> | null>(null);
  const uploadOK = () => {
    uploaderRef.current?.getInstance()?.startUpload();
  };
  // 图片上传成功回调
  const uploadSuccess = (response: any) => {
    if (response.response.success) {
      response.url = baseURL + response.response.data[0].url;
      Message.warning('上传成功');
      onUpdate();
    } else {
      if (response.response.status === 400) {
        response.state = 'error';
        Message.warning('文件上传失败');
      }
    }
  };
  // 上传拦截
  const beforeUpload = (file: ObjectFile) => {
    console.log(file);
    // 检查文件类型是否在允许的列表中
    if (!ALLOWED_MIME_TYPES.includes(file.type as string)) {
      return false;
    }
    // 如果文件类型校验通过，返回 true 允许上传
    return true;
  };
  // 文件校验
  const afterSelect = (file: ObjectFile) => {
    // 1. 文件类型校验
    const isFileTypeValid = ALLOWED_MIME_TYPES.includes(file.type as string);
    if (!isFileTypeValid) {
      Message.warning('不支持的文件类型');
      return false;
    }
    return true;
  };
  useImperativeHandle(ref, () => ({
    uploadOK,
  }));
  return (
    <Upload.Card
      listType="card"
      ref={uploaderRef}
      autoUpload={false}
      useDataURL
      multiple
      action={`${baseURL}/images/upload`}
      headers={{
        Authorization: `Bearer ${token}`,
      }}
      accept={ALLOWED_MIME_TYPES.join(', ')}
      beforeUpload={beforeUpload}
      afterSelect={afterSelect}
      onSuccess={uploadSuccess}
      onPreview={(file) => {
        Dialog.show({
          title: file.name,
          content: <img src={file.imgURL} alt="" className="max-h-400px" />,
          footer: false,
        });
      }}
    />
  );
};
export default forwardRef<UploadCardRef, UploadCardProps>(UploadCard);
